package com.aishua.aishuawallet.engin;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.utils.AndroidUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;


class Task extends TaskObserver implements Runnable,TaskWatcherDog{

	private String requestString;
	private int executeCount;
	private Socket socket;
	private SocketChannel channel;

	Task(String requestString) {
		executeCount = 0;
		this.requestString = requestString;
		// socket = new Socket();
	}

	private IResponseListener response;

	public void setResponseListener(IResponseListener response) {
		this.response = response;
	}

	@Override
	public void run() {

		boolean taskFlag = false;
		try {
			System.out.println("execute===>run");
//			requestBody();
			requestChannelBody();
		} catch (Exception e) {
			System.out.println("requestChannelBody() Exception"+e);
			taskFlag = true;
			e.printStackTrace();
			response.failed("faild not know why");
		}
		try {
			if(channel!=null&&channel.isConnected()){
				System.out.println("run close channel");
				channel.finishConnect();
				channel=null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
//		注销，只请求一次
//		if(taskFlag){
//			if(executeCount< Constant.RETRY_COUNT){
//				System.out.println("task retry count="+executeCount);
////				SystemClock.sleep(60*1000);
//				reExucteTask();
//				return;
//			}else{
//				 if (response != null) {
//					 response.failed("faild not know why");
//				 }
//			}
//		}
		System.out.println("end runnable");

	}

	private void requestChannelBody() throws SocketException, IOException,
            UnsupportedEncodingException {
		executeCount += 1;
		if (channel == null) {
			System.out.println("requestChannelBody count=" + executeCount);
			channel = SocketChannel.open();
		}

		System.out.println("execute===>requestBody==>" + requestString + "");
		// requestString=requestString+"\r\n";
		SocketAddress sa = new InetSocketAddress(Constant.SOCKET_IP,Constant.SOCKET_PORT);
		channel.socket().setSoTimeout(Constant.TIME_OUT);
		channel.connect(sa);
		
		ByteBuffer buffer = ByteBuffer.wrap(requestString.getBytes("utf-8"));
		channel.write(buffer);
		channel.socket().shutdownOutput();
		ByteBuffer receiveBuff = ByteBuffer.allocateDirect(400);
        byte[] bytes=null;  
        int count = 0;
        StringBuffer sb = new StringBuffer();
        while ((count = channel.read(receiveBuff)) >=0) {

        	   receiveBuff.flip();  
               bytes = new byte[count];  
               receiveBuff.get(bytes); 
               String tempStr = new String(bytes,"utf-8");
//               String tempStr = AndroidUtils.bytesToHexString(bytes);
               System.out.println("temp="+tempStr+"temp len="+tempStr.length());
               if (0 == tempStr.length()){
//            	   requestChannelBody();
            	   throw new IOException("temp==null");
               }
               sb.append(tempStr);
//             System.out.println("nio renturn string"+new String(bytes,"utf-8")+"len="+count);
               receiveBuff.clear();  
        }  
//			System.out.println("nio renturn string"+ AndroidUtils.bytesToHexString(bytes));
		System.out.println("callback");
		if (response != null) {

			response.ok(sb.toString());
		}
//		inStream.close();
//		os.close();
//		socket.close();
//		channel.socket().close();
		channel.close();
		channel= null;
//		if(channel!=null&&channel.isConnected()){
//			channel.finishConnect();
////			channel.close();
////			channel=null;
//		}
//		channel = null;
//		channel.finishConnect();
//		channel = null;
		System.out.println("end to body");
	}

	private void requestBody() throws SocketException, IOException,
            UnsupportedEncodingException {
		executeCount += 1;
		System.out.println("execute count=" + executeCount);
		if (socket == null) {
			socket = new Socket();
		}
		socket.setKeepAlive(false);
		// SocketChannel channel = socket.getChannel();
		// channel.socket();
		System.out.println("execute===>requestBody==>" + requestString + "");
		// requestString=requestString+"\r\n";
		SocketAddress sa = new InetSocketAddress(Constant.SOCKET_IP,
				Constant.SOCKET_PORT);
		socket.setSoTimeout(Constant.TIME_OUT);
		// socket.bind(sa);
		// SocketChannel channel = socket.getChannel();
		// channel.connect(sa);
		socket.connect(sa, Constant.TIME_OUT);
		OutputStream os = socket.getOutputStream();
		// OutputStreamWriter osw = new OutputStreamWriter(os);
		// BufferedWriter bw = new BufferedWriter(osw);

		// bw.write(socketReq.trim() + "\r\n");
		// bw.flush();

		byte[] buffer = requestString.getBytes("utf-8");
		os.write(buffer);
		os.flush();
		socket.shutdownOutput();
		// os.close();
		InputStream inStream = socket.getInputStream();
//		SystemClock.sleep(10);
		int len = inStream.available();
//		System.out.println("len" + len);
		byte[] backBuff = new byte[10];
//		inStream.read(backBuff);
//		String backStr = new String(backBuff, "utf-8");
//		System.out.println("DataInputStream" + backStr);
		// int len = 0;
		String backString = null;

		StringBuffer sb = new StringBuffer();
		 while((len=inStream.read(backBuff))!=-1){
		 System.out.println("len====>"+len);
		 sb.append(new String(backBuff,0,len,"utf-8"));
		 // backString = new String(backBuff,"utf-8");
		 System.out.println("backString="+sb.toString());
		 }
		System.out.println("buffRealString=" + sb.toString());
		// InputStreamReader isr = new InputStreamReader(inStream, "utf-8");
		// BufferedReader br = new BufferedReader(isr);
		// String read = br.readLine();
		// isr.close();
		// br.close();
		System.out.println("callback");
		if (response != null) {
//			response.ok(sb.toString());
		}
		inStream.close();
		os.close();
		socket.close();
		socket = null;
		System.out.println("end to body");
	}
	@Override
	public void taskFaild() {
		run();
	}

}
